<template>
  <div class="profile-password common-mobile-view">
    <el-form ref="ruleFormRef"
             :model="passwordInfo"
             :rules="rules" label-width="auto">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="passwordInfo.oldPassword" type="password" show-password clearable/>
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordInfo.newPassword" type="password" show-password clearable/>
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordInfo.confirmPassword" type="password" show-password clearable/>
      </el-form-item>
    </el-form>

    <div class="button-container">
      <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store/user.ts'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { profilePasswordRules } from '@/utils/element/elRules.ts'

const userStore = useUserStore()

const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules>(profilePasswordRules)

const passwordInfo = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (passwordInfo.newPassword !== passwordInfo.confirmPassword) {
        ElMessage.error('确认密码和新密码不一致')
        return
      }

      await userStore.updateAccountPassword(passwordInfo.oldPassword, passwordInfo.newPassword)
      ElMessage.success('更改密码成功')
    }
  })
}
</script>

<style scoped lang="scss">
.profile-password {
  display: flex;
  flex-direction: column;
  gap: 5px;

  .button-container {
    align-self: center;
  }
}
</style>
